<template>
  <div>
  <!-- 面包导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <!-- 上面工具栏 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            clearable=""
            placeholder="请输入角色名查询"
            v-model="roleVo.roleName"
            class="input-with-select"
            @clear="getRoleList">
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button
            type="success"
            icon="el-icon-circle-plus-outline"
            @click="addDialogVisible=true">添加
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button
            icon="el-icon-download"
            @click="downExcel">导出
          </el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
     <template> 
        <el-table
          v-loading="loading"
          :data="roleData"
          style="width: 100%;margin-top:20px;"
          max-height="450"
        >
          <el-table-column prop="id" label="ID" width="50"></el-table-column>
          <el-table-column prop="roleName" label="角色名" width="180"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          <el-table-column prop="status" label="是否可用" width="100">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status"
                         :active-value="1"
                         :inactive-value="0"
                         @change="changRoleStatus(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="200"></el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                @click="grant(scope.row.id)"
                type="text"
                icon="el-icon-present"
                size="small"
              >授权
              </el-button>
              <el-button @click="edit(scope.row)" type="text" icon="el-icon-edit" size="small">编辑</el-button>
              <el-button
                @click="del(scope.row.id)"
                type="text"
                icon="el-icon-delete"
                size="small"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template> 

      <!-- 分页部分 -->
      <el-pagination
        background
        style="margin-top:10px;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[7, 16, 32, 64]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!--添加弹框-->
     <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="closeAdd">
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRoles">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="描述信息" prop="remark">
            <el-input type="textarea" v-model="addForm.remark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addRole"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑弹框 -->
      <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%" @close="closeEdit">
        <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="addFormRoles">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="描述信息" prop="remark">
            <el-input type="textarea" v-model="editForm.remark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="updateRole"
            :loading="btnLoading"
            :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>

       <!-- 角色授权弹出框 -->
      <el-dialog title="分配菜单权限" :visible.sync="grantDialogVisible" width="38%">
        <el-checkbox v-model="deptCheckStrictly" label="父子联动" @change="handleCheckedTreeConnect($event)"></el-checkbox>
        <span>
          <el-tree
            style="
                margin-top: 5px;
                border: 1px solid #e5e6e7;
                background: #FFFFFF none;
                border-radius:4px "
            :auto-expand-parent="false"
            :data="data"
            show-checkbox=""
            node-key="id"
            :props="defaultProps"
            :check-strictly=!deptCheckStrictly
            ref="tree"
            highlight-current></el-tree>
          <!-- check-strictly -->
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="grantDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            icon="el-icon-setting"
            @click="authority"
            :loading="btnLoading"
            :disabled="btnDisabled">授 权</el-button>
        </span>
      </el-dialog>

      
    </el-card>
  </div>
</template>
<script>
import { findRolePage,toExcel,findRoleMenu,roleAdd,roleUpdate,
roleDelete,roleUpdateStatus,authority} 
from '@/api/system/role';

export default {
  name : 'Role',
  components : {

  },
  data () {
      return {
        deptCheckStrictly: true,//父子联动
        btnLoading: false,
        btnDisabled: false,
        loading: true,
        size: 7,
        total: 100,
        current: 1,
        roleData: [], //角色表格数据
        addForm: {}, //添加数据
        editForm: {}, //编辑数据
        addDialogVisible: false, //添加弹框的显示
        editDialogVisible: false, //编辑弹框
        grantDialogVisible: false, //授权弹出框
        data: [],
        open: [], //展开
        grantId: '',
        defaultProps: {
          children: 'children',
          label: 'menuName'
        },
        roleVo: {
          roleName: ''
        },
        addFormRoles: {
          roleName: [
            {
              required: true,
              message: '请输入角色名称',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 15,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          remark: [
            {
              required: true,
              message: '请输入角色描述信息',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 20,
              message: '长度在 5 到 20 个字符',
              trigger: 'blur'
            }
          ]
        } //添加验证规则
      }
    },
    created(){
      this.getRoleList();
      setTimeout(() => {
        this.loading = false
      },500)
    },
    methods : {
      //加载角色列表
      getRoleList(){
        findRolePage(this.current,this.size,this.roleVo).then(res =>{
          //console.log(res)
          if(res.code == 200){
            this.roleData = res.data.records
            this.total = res.data.total
          }
        })
      },
      //搜索
      search(){
        this.current = 1;
        this.getRoleList();
      },
      //导出数据到excel
      async downExcel(){
       toExcel().then(res => {
           console.log(res)
          //  if (res.headers['content-type'] === 'application/json') {
          //     return this.$message.error('Subject does not have permission')
          //   }
            
            let url = window.URL.createObjectURL(res);// 将二进制文件转化为可访问的url
            //console.log(url);
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = '角色列表.xls';
            a.click();
            window.URL.revokeObjectURL(url);           
       })       
      },
      //改变角色禁用状态
      async changRoleStatus(row){
          try{
            const res = await roleUpdateStatus(row.id,row.status)
            if(res.code === 200){
              this.$message.success('更新状态更新')
            }
          }catch(e){
            row.status = row.status ? 0 : 1;
          }
      },
      //当每页条数改变
      handleSizeChange(val){
        this.size = val
        this.getRoleList()
      },
      //当前页码改变
      handleCurrentChange(val){
        this.current = val
        this.getRoleList()
      },
      //打开授权
      async grant(id){
        this.deptCheckStrictly = true
        //加载所有菜单以及角色拥有的菜单权限id
        const res = await findRoleMenu(id)
        if(res.code === 200){
          //默认选中的树的数据
          let that = this
          setTimeout(function() {
            res.data.mids.forEach(value => {
              that.$refs.tree.setChecked(value,true,false)
            })
          },100)
          this.data = res.data.tree
          this.grantId = id //需要授权的id
        }
        this.grantDialogVisible = true
      },
      //父子联动
      handleCheckedTreeConnect(value){
        this.deptCheckStrictly = !value
      },
      //确认授权
      async authority(){
        this.btnDisabled = true
        this.btnLoading = true
        //getHalfCheckedKeys： 取父节点 若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组
        //getCheckedKeys： 取子节点 若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组
        console.log(this.grantId);
        console.log([].concat(this.$refs.tree.getCheckedKeys(),this.$refs.tree.getHalfCheckedKeys()))
        const res = await authority(this.grantId,[].concat(this.$refs.tree.getCheckedKeys(),this.$refs.tree.getHalfCheckedKeys()))
        if(res.code === 200){
          this.$message.success('角色授权成功')
        }else{
          this.$message.fail('授权失败')
        }
        this.btnDisabled = false
        this.btnLoading = false
        this.grantDialogVisible = false
      },
      //添加
      async addRole(){
        this.$refs.addFormRef.validate(async valid=>{
          if(!valid){

          }else{
            this.btnDisabled = true
            this.btnLoading = true
            const res = await roleAdd(this.addForm)
            if(res.code === 200){
              this.$message.success('添加成功')
              this.addDialogVisible = false
              this.btnDisabled = false
              this.addForm = {}
              this.getRoleList()
            }else{
               this.$message.success('添加失败')
              this.addDialogVisible = false
              this.btnDisabled = false
              this.addForm = {}
            }
          }
        })
      },
      //关闭添加弹框
      closeAdd()
      {
        this.$refs.addFormRef.clearValidate()
        this.addForm = {}
      },
      //删除角色
      async del(id){
        const res = await this.$confirm(
          '此操作将永久删除该角色们是否继续?',
          '提示',
          {
            confirmButtonText : '确定',
            cancelButtonText : '取消',
            type: 'warning'
          }
        ).catch(()=>{
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
        if(res === 'confirm'){
          await roleDelete(id).then(res => {
            if(res.code === 200){
              this.$message.success('删除成功')
              this.getRoleList()
            }else{
              this.$message.success('删除失败')
            }
          })
        }
      },
      //打开编辑框
      async edit(row){
        console.log(row);
        this.editForm = row
        this.editDialogVisible = true
      },
      //更新角色
      async updateRole(){
        this.$refs.editFormRef.validate(async valid =>{
          if(!valid){

          }else{
            this.btnDisabled = true
            this.btnLoading = true
            const res = await roleUpdate(this.editForm.id,this.editForm)
            if(res.code === 200){
              this.$notify({
                title:'成功',
                message: '角色信息更新',
                type:'success'
              })
              this.getRoleList()
            }
            this.editDialogVisible = false
            this.btnDisabled = false
            this.btnLoading = false
            this.editForm = {}
          }
        })
      },
      //关闭编辑框
      closeEdit(){
        this.$refs.editFormRef.clearValidate()
        this.editForm = {}
      }

    }
    
}
</script>